package com.financing.wap.web.controller.api;



import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.dto.MessageJpushDTO;
import com.financing.wap.dto.MessageJpushUserPhoneAliasDTO;
import com.financing.wap.dto.NewsDTO;
import com.financing.wap.dto.TagNewsDTO;
import com.financing.wap.dto.TagProductDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IMessageJpushUserPhoneAliasService;
import com.financing.wap.service.INewsService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.MemcacheCacheHelper;
import com.financing.wap.vo.QueryNewsVo;
import com.financing.wap.vo.TagRelateVo;
import com.financing.wap.web.controller.BaseController;

/**
 * 资讯类
 * @author Marco
 *
 */
@Controller("apiNewsController")
@RequestMapping("/api/news")
public class NewsController  extends BaseController{

	Logger logger = Logger.getLogger(getClass());



	@Autowired
	private INewsService newsService;

	@Autowired
	private IMessageJpushUserPhoneAliasService messageJpushUserPhoneAliasService;
	/**
	 * 资讯列表
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, HttpServletResponse response,QueryNewsVo queryVo){
		ResultMap result = new ResultMap();
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		try {

			Pager pager = new Pager();
			if(null != queryVo.getType() && queryVo.getType().contains(",")){
				queryVo.setTypes(StringUtils.split(queryVo.getType(),","));
				queryVo.setType(null);
			}
			Integer count = newsService.getNewsListCount(queryVo);
			pager.setTotalCount(count);
			pager.setPageSize(queryVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			queryVo.setStart(pager.getStartIndex());
//			//多个类型查询
//			if(!StringUtils.isBlank(queryVo.getType())){
//				queryVo.setTypes(StringUtils.split(queryVo.getType(),","));
//			}
			List<NewsDTO> newsList = newsService.getNewsList(queryVo);

			// 更新fp_fa_user 中 U_LAST_JPUSH_DATE 字段 表示已读消息
			updateLastDate(request);

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", newsList);
			result.setAttribute("pager", pager);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 * 根据类型查询资讯
	 * @return
	 */
	@RequestMapping("/listByType")
	@ResponseBody
	public ResultMap listByTpey(HttpServletRequest request, HttpServletResponse response,QueryNewsVo queryVo){
		ResultMap result = new ResultMap();
		try {
			logger.info("In NewsController listByTpey Begin!");
			List<NewsDTO> newsList = newsService.getNewsList(queryVo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", newsList);
			logger.info("In NewsController listByTpey end!");
		} catch (Exception e) {
			logger.error("error NewsController listByTpey:",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 * 展示客户资料
	 * @return
	 */
	@RequestMapping("/{id}")
	@ResponseBody
	public ResultMap view(@PathVariable int id,Integer newId,HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		try {
			if(newId != null){
				id = newId;
			}
			NewsDTO dto = newsService.searchNewsById(id);
			result.setStatus(STATUS.SUCCESS);
			result.setAttribute("dto", dto);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}


	/**
	 * 根据产品ID获取相关资讯
	 * @return
	 */
	@RequestMapping("/aboutNews/{pid}")
	@ResponseBody
	public ResultMap aboutNewsByPid(HttpServletRequest request, HttpServletResponse response,TagRelateVo  tagRelateVo){
		ResultMap result = new ResultMap();
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		try {
			Pager pager = new Pager();
			Integer count = newsService.getAboutNewsByPidCount(tagRelateVo);
			pager.setTotalCount(count);
			pager.setPageSize(tagRelateVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			tagRelateVo.setStart(pager.getStartIndex());

			List<TagNewsDTO> newsList = newsService.getAboutNewsByPid(tagRelateVo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", newsList);
			result.setAttribute("pager", pager);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}

	/**
	 * 根据资讯ID获取相关产品
	 * @return
	 */
	@RequestMapping("/aboutProducts/{nid}")
	@ResponseBody
	public ResultMap aboutProductsByNid(HttpServletRequest request, HttpServletResponse response,TagRelateVo  tagRelateVo){
		ResultMap result = new ResultMap();
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		try {
			Pager pager = new Pager();
			Integer count = newsService.getAboutProductsByPidCount(tagRelateVo);
			pager.setTotalCount(count);
			pager.setPageSize(tagRelateVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			tagRelateVo.setStart(pager.getStartIndex());

			List<TagProductDTO> productsList = newsService.getAboutProductsByPid(tagRelateVo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", productsList);
			result.setAttribute("pager", pager);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}

	/**
	 * 根据标签ID获取相关产品
	 * @return
	 */
	@RequestMapping("/aboutTagProducts/{tid}")
	@ResponseBody
	public ResultMap aboutTagProductsByTagid(HttpServletRequest request, HttpServletResponse response,TagRelateVo  tagRelateVo){
		ResultMap result = new ResultMap();
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		try {
			Pager pager = new Pager();
			Integer count = newsService.getAboutTagProductsByPidCount(tagRelateVo);
			pager.setTotalCount(count);
			pager.setPageSize(tagRelateVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			tagRelateVo.setStart(pager.getStartIndex());

			List<TagProductDTO> productsList = newsService.getAboutTagProductsByPid(tagRelateVo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", productsList);
			result.setAttribute("pager", pager);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}

	/**
	 * 根据标签ID获取相关资讯
	 * @return
	 */
	@RequestMapping("/aboutTagNews/{tid}")
	@ResponseBody
	public ResultMap aboutTagNewsByTagid(HttpServletRequest request, HttpServletResponse response,TagRelateVo  tagRelateVo){
		ResultMap result = new ResultMap();
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		try {
			Pager pager = new Pager();
			Integer count = newsService.getAboutTagNewsByPidCount(tagRelateVo);
			pager.setTotalCount(count);
			pager.setPageSize(tagRelateVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			tagRelateVo.setStart(pager.getStartIndex());

			List<TagProductDTO> productsList = newsService.getAboutTagNewsByPid(tagRelateVo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", productsList);
			result.setAttribute("pager", pager);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 * 极光推送资讯列表
	 * @return
	 */
	@RequestMapping("/jPushlist")
	@ResponseBody
	public ResultMap jPushlist(HttpServletRequest request, HttpServletResponse response,QueryNewsVo queryVo){
		ResultMap result = new ResultMap();



		try {

			String pageNo = request.getParameter("pageNo");
			if(StringUtils.isBlank(pageNo)){
				pageNo="1";
			}
			Pager pager = new Pager();
			if(null != queryVo.getType() && queryVo.getType().contains(",")){
				queryVo.setTypes(StringUtils.split(queryVo.getType(),","));
				queryVo.setType(null);
			}
			Integer count = newsService.getJPushListCount(queryVo);
			pager.setTotalCount(count);
			pager.setPageSize(queryVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			queryVo.setStart(pager.getStartIndex());

			List<MessageJpushDTO> newsList = newsService.getJPushList(queryVo);

			// 更新fp_fa_user 中 U_LAST_JPUSH_DATE 字段 表示已读消息
			updateLastJPushListDate(request);

			// 跳转地址解密
			for (int i = 0; i < newsList.size(); i++) {
				newsList.get(i).setFpJpushRedrict(new String(Base64.decode(newsList.get(i).getFpJpushRedrict().getBytes())));
				if(newsList.get(i).getFpJpushRedrict().indexOf("keList")>0){
					newsList.get(i).setWjt(true);
				}
			}

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", newsList);
			result.setAttribute("pager", pager);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}

	/**
	 * 极光推送资讯列表-店铺消息
	 * @return
	 */
	@RequestMapping("/jPushlistShop")
	@ResponseBody
	public ResultMap jPushlistShop(HttpServletRequest request, HttpServletResponse response,QueryNewsVo queryVo){
		ResultMap result = new ResultMap();



		try {

			String pageNo = request.getParameter("pageNo");
			if(StringUtils.isBlank(pageNo)){
				pageNo="1";
			}
			Pager pager = new Pager();
			if(null != queryVo.getType() && queryVo.getType().contains(",")){
				queryVo.setTypes(StringUtils.split(queryVo.getType(),","));
				queryVo.setType(null);
			}
			UserDTO user = getSession(true).getUser();
			if(user != null && user.getId()!=null) {    //未登录不显示 交易通知 竞价通知
				MessageJpushUserPhoneAliasDTO dto = new MessageJpushUserPhoneAliasDTO();
				dto.setFpUserId(user.getId());
				MessageJpushUserPhoneAliasDTO phoneAlias = messageJpushUserPhoneAliasService.queryMessageJpushUserPhoneAlias(dto);
				if(null != phoneAlias ) {
					queryVo.setMsgRec(phoneAlias.getFpJpushAliasShop());
				}
			}

			Integer count = newsService.getJPushListShopCount(queryVo);
			pager.setTotalCount(count);
			pager.setPageSize(queryVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			queryVo.setStart(pager.getStartIndex());

			List<MessageJpushDTO> newsList = newsService.getJPushListShop(queryVo);

			// 更新fp_fa_user 中 U_LAST_JPUSH_SHOP_DATE 字段 表示已读消息
			updateLastJPushListShopDate(request);

			// 跳转地址解密
			for (int i = 0; i < newsList.size(); i++) {
				newsList.get(i).setFpJpushRedrict(new String(Base64.decode(newsList.get(i).getFpJpushRedrict().getBytes())));;
			}

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", newsList);
			result.setAttribute("pager", pager);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	private void updateLastJPushListDate(HttpServletRequest request) throws Exception {
		Map<String, Object> parMap = new HashMap<String, Object>();
		UserDTO user =	 this.getSession().getUser();
		//从cookies 获取设备号
		//根据 设备号获取用户id
		if(user != null){
			parMap.put("faId", user.getId());

			// 更新fp_fa_user 中 U_LAST_JPUSH_DATE 字段 表示已读消息
			newsService.updateLastJPushListDate(parMap);
		}else{

			logger.info("request.getCookies begin!");

			Cookie[] cookies = request.getCookies();
			String jpush_alias = "";
			if(cookies != null){
				for(Cookie cookie : cookies ){
					if(Constants.JPUSH_ALIAS.equals(cookie.getName())){
						jpush_alias = cookie.getValue();
					}
				}
			}

			logger.info("request.getCookies jpush_alias:"+jpush_alias);

			if(StringUtils.isNotBlank(jpush_alias)){
				MessageJpushUserPhoneAliasDTO dto = new MessageJpushUserPhoneAliasDTO();
				dto.setFpJpushAlias(jpush_alias);
				dto = messageJpushUserPhoneAliasService.queryMessageJpushUserPhoneAlias(dto);
				if(dto!= null && dto.getFpUserId() != null){
					logger.info("request.getCookies  dto.getFpUserId():"+ dto.getFpUserId());
					//存在   设备号获取用户id 就更新 数据库的时间
					parMap.put("faId", dto.getId());
					// 更新fp_fa_user 中 U_LAST_JPUSH_DATE 字段 表示已读消息
					newsService.updateLastJPushListDate(parMap);
				}else{
					logger.info("request.getCookies  mcc.se:"+ jpush_alias);
					//不存在   设备号获取用户id 就更新 缓存的时间
					MemcacheCacheHelper.mcc.set(jpush_alias+"_lastJPushTime",DateUtil.getDate("yyyy-MM-dd HH:mm:ss"));
				}

			}
		}

	}
	private void updateLastJPushListShopDate(HttpServletRequest request) throws Exception {
		Map<String, Object> parMap = new HashMap<String, Object>();
		UserDTO user =	 this.getSession().getUser();
		//从cookies 获取设备号
		//根据 设备号获取用户id
		if(user != null){
			parMap.put("faId", user.getId());

			// 更新fp_fa_user 中 U_LAST_JPUSH_DATE 字段 表示已读消息
			newsService.updateLastJPushListShopDate(parMap);
		}

	}

	private void updateLastDate(HttpServletRequest request) throws Exception {
		Map<String, Object> parMap = new HashMap<String, Object>();
		UserDTO user =	 this.getSession().getUser();
		//从cookies 获取设备号
		//根据 设备号获取用户id
		if(user != null){
			parMap.put("faId", user.getId());

			// 更新fp_fa_user 中 U_LAST_JPUSH_DATE 字段 表示已读消息
			newsService.updateLastDate(parMap);
		}else{
			Cookie[] cookies = request.getCookies();
			String jpush_alias = "";
			if(cookies != null){
				for(Cookie cookie : cookies ){
					if(Constants.JPUSH_ALIAS.equals(cookie.getName())){
						jpush_alias = cookie.getValue();
					}
				}
			}
			if(StringUtils.isNotBlank(jpush_alias)){
				MessageJpushUserPhoneAliasDTO dto = new MessageJpushUserPhoneAliasDTO();
				dto.setFpJpushAlias(jpush_alias);
				dto = messageJpushUserPhoneAliasService.queryMessageJpushUserPhoneAlias(dto);
				if(dto!= null && dto.getFpUserId() != null){
					parMap.put("faId", dto.getId());

					// 更新fp_fa_user 中 U_LAST_JPUSH_DATE 字段 表示已读消息
					newsService.updateLastDate(parMap);
				}else{
					logger.info("request.getCookies  mcc.se:"+ jpush_alias);
					//不存在   设备号获取用户id 就更新 缓存的时间
					MemcacheCacheHelper.mcc.set(jpush_alias+"_lastNewsTime",DateUtil.getDate("yyyy-MM-dd HH:mm:ss"));
				}
			}
		}

	}
}
